package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class OpenIdController {
    @Autowired
    Environment environment;

    @RequestMapping("openid")
    public String[] openId(){
        String port = environment.getProperty("server.port");

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String collect = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","));
        Jwt jwt = (Jwt) authentication.getPrincipal();
        String id = jwt.getSubject();
        Map<String, Object> claims = jwt.getClaims();
        URL issuer = jwt.getIssuer();
        return new String[]{String.valueOf(port+"||"+id+"||"+issuer.toString()+"||"+claims),collect};
    }
}